﻿import requests
import io


class SeafAPI(object):
	def __init__(self, address, username, password):
		self.address = address
		token = self.get_token({'username': username, 'password': password})
		self.token = token['token']

	def get_token(self, data):
	    url = '{address}/api2/auth-token/'.format(address=self.address)
	    res = requests.post(url, data=data)
	    res.raise_for_status()
	    return res.json()


	def get_upload_link(self, repo_id):
	    url = '{address}/api2/repos/{repo_id}/upload-link/'.format(address=self.address, repo_id=repo_id)
	    res = requests.get(
	        url, headers={'Authorization': 'Token {token}'.format(token=self.token)}
	    )
	    res.raise_for_status()
	    return res.json()


	@property
	def libraries(self):
	    url = '{address}/api2/repos/'.format(address=self.address)
	    res = requests.get(
	        url, headers={'Authorization': 'Token {token}'.format(token=self.token)}
	    )
	    res.raise_for_status()
	    return res.json()


	def upload_file(self, upload_link, fp, parent_dir='/'):
	    if isinstance(fp, io.IOBase):
	        data = {'filename': fp.name.split('/')[-1], 'parent_dir': parent_dir}
	        files = {'file': fp}
	    elif isinstance(fp, str):
	        data = {'filename': fp.split('/')[-1], 'parent_dir': parent_dir}
	        files = {'file': open(fp, 'rb')}
	    else:
	        raise TypeError("fp type is invalid.")
	    res = requests.post(upload_link, data=data, files=files, headers={'Authorization': 'Token {token}'.format(token=self.token)})
	    res.raise_for_status()
	    return res.text


	def create_dir(self, repo_id, dir_name):
	    url = "{address}/api2/repos/{repo_id}/dir/".format(address=self.address, repo_id=repo_id)
	    data = dict(operation="mkdir")
	    params = {"p": dir_name if dir_name.startswith("/") else "/"+dir_name}
	    headers = {'Authorization': 'Token {token}'.format(token=self.token)}
	    res = requests.post(url, data=data, params=params, headers=headers)
	    res.raise_for_status()
	    return res.text


	def get_dir(self, repo_id, dir_name):
	    url = "{address}/api/v2.1/repos/{repo_id}/dir/detail/".format(address=self.address, repo_id=repo_id)
	    headers = {'Authorization': 'Token {token}'.format(token=self.token)}
	    params = {"path": dir_name}
	    res = requests.get(url, headers=headers, params=params)
	    return res.json()

	@property
	def all_repo_id(self):
		libraries = self.libraries
		repos = {lib.get('name'): lib.get('id') for lib in libraries}
		return repos

	def delete_file(self, repo_id, fp):
		url = "{address}/api2/repos/{repo_id}/file/".format(address=self.address, repo_id=repo_id)
		headers = {'Authorization': 'Token {token}'.format(token=self.token)}
		params = {"p": fp}
		res = requests.delete(url, headers=headers, params=params)


if __name__ == '__main__':
    address = 'http://www.vmnas.com:8000'
    api = SeafAPI(address, 'a@a.com', '1')
    repos = api.all_repo_id
    repo_id = repos.get("私人资料库")
    upload_link = api.get_upload_link(repo_id)
    print(api.upload_file(upload_link, 'TODO.md'))
    print(api.get_dir(repo_id, "IPYNB"))
